﻿app.controller("ngNavController", function ($scope, $window, $q, LoginService, $location, $route, $http) {
    $scope.loggingIn = false;
    $scope.token = $window.sessionStorage.getItem("token");

    $scope.user = {};

    $scope.user.username = "user01";
    $scope.user.password = "pass01";

    $scope.register = false;

    $scope.errorMessage = false;

    $scope.login = function () {
        $scope.loggingIn = true;
        $scope.errorMessage = false;

        LoginService.processLogin($scope.user.username, $scope.user.password)
        .then(function () {
            $scope.token = $window.sessionStorage.getItem("token");
            $("#login-modal").modal("hide");
            $scope.loggingIn = false;
        }, function (status) {
            $scope.token = status;
            $scope.loggingIn = false;
            $scope.user.password = "";
            $scope.errorMessage = "Oops... There was an error. Please try again.";
        });
    };

    $scope.logout = function () {
        LoginService.processLogout().then(function () {
            $scope.token = $window.sessionStorage.getItem("token");
            $route.reload();
            $location.path("/");
        }, function (status) {
            $scope.token = status;
        });
    };

    $scope.registerUser = function () {
        $scope.loggingIn = true;
        $scope.errorMessage = false;

        $http.post("/api/Account/Register", $scope.regModel).success(function () {
            $scope.user.username = $scope.regModel.UserName;
            $scope.user.password = "";
            $scope.regModel.UserName = "";
            $scope.regModel.Email = "";
            $scope.regModel.Password = "";
            $scope.regModel.ConfirmPassword = "";
            $scope.register = false;
            $scope.loggingIn = false;
        }).error(function (data) {
            console.log(data);
            $scope.loggingIn = false;
            $scope.regModel.Password = "";
            $scope.regModel.ConfirmPassword = "";
            $scope.errorMessage = "Oops... There was an error. Please try again.";
        });
    }
});